package com.abocode.aichat.server.delivery.outbound;


import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.delivery.AbstractServerDeliver;
import com.abocode.aichat.server.delivery.RelayResult;
import com.abocode.aichat.server.entity.Entity;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.stanza.Stanza;
import com.abocode.aichat.server.stanza.StanzaImpl;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * Created by franky-8.
 */
public class OutboundServerDeliver extends AbstractServerDeliver<Replies> implements MessageDelegateListener {

//    protected HashMap<String, TcpClient> replyWorker;

    class OutboundReplyCallable implements Callable<RelayResult> {
        private ServerRuntimeContext serverRuntimeContext;

        public Stanza stanza;

        public OutboundReplyCallable(ServerRuntimeContext serverRuntimeContext, Stanza stanza) {
            this.stanza = stanza;
            this.serverRuntimeContext = serverRuntimeContext;
        }

        @Override
        public RelayResult call() throws Exception {
            try {
                //拿到链接
                Entity entity = stanza.findTo();
                if (entity != null) {
                    List<Channel> channles = getServerRuntimeContext().getProtocolChannelRegistry().get(entity);
                    if(channles!=null && !channles.isEmpty()){
                        for(Channel channel:channles){
                            serverRuntimeContext.getWorker().execute(channel,stanza);
                        }
                    }
                }
            } catch (Exception ex) {
                return new RelayResult("fail", 500);
            }
            return new RelayResult("succ", 200);
        }
    }

    @Override
    public void deliver(Replies replies, Stanza stanza) {
        Future<RelayResult> future = executor.submit(new OutboundReplyCallable(getServerRuntimeContext(),stanza));
    }

    @Override
    public void handleMessage(String msg) {
        Stanza stanza = JSON.parseObject(msg, StanzaImpl.class);
        stanza.validate();
        deliver(null,stanza);
    }
}
